from airtest.core.api import *
from poco.drivers.android.uiautomation import AndroidUiautomationPoco
import logging
import requests
import cv2
from rapidfuzz import fuzz
import random
# import sys
from multiprocessing import Process, Queue
import re
from threading import Thread
import subprocess
# 屏蔽airtest的logger信息
logging.getLogger("airtest").setLevel(logging.ERROR)
# 创建一个logger
logger = logging.getLogger("淘宝")
logger.setLevel(logging.DEBUG)


def get_devices_list():
    """获取所有在线设备

    Returns:
        _type_: 设备列表
    """
    res = subprocess.run("adb devices",
                         capture_output=True,
                         text=True,
                         shell=True)
    # print(res.stdout, res.stderr)
    result = res.stdout
    result = result.splitlines()[1:]
    logger.info(result)
    devices_list = []
    for res in result:
        device = res.split('\t')[0]
        if device != '':
            devices_list.append(device)
    return devices_list


class taobao():

    def __init__(self, dev):
        ###################初始化###################
        self.dev = connect_device(
            f"android://127.0.0.1:5037/{dev}"  #?cap_method=javacap&touch_method=adb
        )

        # if dev:
        self.dev.wake()
        # start_app("com.ss.android.ugc.aweme.lite")
        self.poco = AndroidUiautomationPoco(device=self.dev,
                                            use_airtest_input=True,
                                            screenshot_each_action=False)
        self.width, self.height = self.poco.get_screen_size()
        self.start_point = (self.width / 5, self.height * 0.8)  # 中点偏上位置
        self.end_point = (self.width / 5, self.height * 0.3)  # 中点偏下位置
        self.start_point_1 = (self.width / 5, self.height * 0.6)  # 中点偏上位置
        self.end_point_1 = (self.width / 5, self.height * 0.5)  # 中点偏下位置
        self.left_point = (self.width * 0.2, self.height / 2)
        self.right_point = (self.width * 0.8, self.height / 2)
        self.first_start = True
        # 创建一个handler，用于写入日志文件
        fh = logging.FileHandler(f"./log/{dev}_log.txt", encoding="utf-8")
        fh.setLevel(logging.DEBUG)
        # 再创建一个handler，用于输出到控制台
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)  # 设置控制台日志级别
        # 定义handler的输出格式
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fh.setFormatter(formatter)
        ch.setFormatter(formatter)
        # 给logger添加handler
        logger.addHandler(fh)
        logger.addHandler(ch)
        logger.info(dev)
        ###################任务清单###################
        self.quests_list = []

    def page_contents(self):
        contents = []
        freeze_poco = self.poco.freeze()
        if freeze_poco("android.widget.TextView").exists():
            for child in freeze_poco("android.widget.TextView"):
                contents.append(child.get_text())
        if contents:
            # contents = ' '.join(contents)
            logger.info(contents)
            return contents
        else:
            return None

    def poco_text_page(self):
        freeze_poco = self.poco.freeze()
        content = self.page_contents()
        if not content:
            return True

        # 弹出任务界面
        if '做任务赚元宝' in content:
            swipe(self.start_point, self.end_point)
            quests = []
            for p in freeze_poco(textMatches=r".*?/.*?"):
                quest_name = p.get_text()
                quest_detail = p.sibling()[-1].get_text()
                quest_status = p.parent().sibling()[-1].get_text()
                temp = [quest_name, quest_detail, quest_status]
                logger.info(temp)
                if quest_status == '已完成':
                    continue
                elif "购买超值商品赚元宝" in quest_name or "蚂蚁森林" in quest_name or "斗地主" in quest_name:
                    continue
                else:
                    quests.append(temp)
            if quests:
                print(quests)
                self.quests_list = quests
                target_quest = self.quests_list[0][0]
                logger.info(target_quest)
                self.poco(text=target_quest).click()
                return True
            else:
                return False
        # 浏览红包弹出界面
        if '恭喜获得浏览红包' in content:
            if freeze_poco(text="去使用").exists():
                freeze_poco(text="去使用").click()
                return True
        elif '签到领现金' in content:
            if freeze_poco(text="继续领现金").exists():
                freeze_poco(text="继续领现金").click()
                # return True
                self.poco(textMatches=r".*?/.*?").wait_for_appearance()
                return True
            elif freeze_poco(text="立即签到").exists():
                freeze_poco(text="立即签到").click()
                self.poco(textMatches=r".*?/.*?").wait_for_appearance()
                return True

        # 搜索宝贝提示界面
        if '搜索你喜欢的宝贝' in content or '逛精选好货赚元宝' in content:
            # 立即领3200元宝
            if freeze_poco(textMatches=r"立即领\d+元宝").exists():
                freeze_poco(textMatches=r"立即领\d+元宝").click()
                return True
        if '猜你想搜' in content:
            index = content.index(r'猜你想搜')
            next_text = content[index + 1]
            if freeze_poco("android.widget.ListView").exists():
                logger.info(f"搜索-> {next_text}")
                self.poco(text=next_text).click()
                return True
        elif '浏览得奖励' in content:
            while True:
                freeze_poco = self.poco.freeze()
                content = self.page_contents()
                if '任务已完成，逛逛优惠宝贝~' in content:
                    keyevent("back")
                    keyevent("back")
                    return True
        if '任务已完成，逛逛优惠宝贝~' in content:
            keyevent("back")
            keyevent("back")
            return True
        elif '任务完成' in content:
            keyevent("back")
            # keyevent("back")
            return True
        if "滑动浏览" in content or '继续浏览' in content:
            while True:
                swipe(self.start_point, self.end_point)
                swipe(self.end_point, self.start_point)
                freeze_poco = self.poco.freeze()
                content = self.page_contents()
                if "滑动浏览" in content or '继续浏览' in content:
                    continue
                elif '任务完成' in content:
                    while not self.poco(text="继续领现金").exists():
                        sleep(2)
                        keyevent("back")
                    return True
        elif "剩" in content and "今" in content:
            logger.info("休眠15秒")
            sleep(20)
            while not self.poco(text="继续领现金").exists():
                sleep(2)
                keyevent("back")

    def get_coin(self):
        while True:
            if self.poco(text="倒计时").exists():
                print(self.poco(text="倒计时").get_text(), end='\r')
            if self.poco(text="点击领取").exists():
                self.poco(text="点击领取").click()


def start():
    devs = get_devices_list()
    t = taobao(dev=devs[0])
    # t.get_coin()
    while True:
        if t.poco_text_page():
            pass
        else:
            logger.info("任务完成")
            while True:

                break
            break


if __name__ == '__main__':
    start()
